<?php

namespace App\Http\Controllers\Backstage;

use App\Http\Controllers\Backstage\BCommonController;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use App\Models\BackstageModel;
use App\Models\CommonModel;
use Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Libary\Captcha\Code;

// require_once '../app/libary/captcha/Code.class.php';

class ProductController extends BCommonController
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/backstage/product/index';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    // public function __construct()
    // {
    //     $this->middleware('guest', ['except' => 'logout']);
    // }

    public function index(){
        if(isset($_GET['type_id']) && intval($_GET['type_id'])!=0){
            $type_id = intval($_GET['type_id']);
            if(isset($_GET['keywords'])){
                $keywords = trim($_GET['keywords']);
                $list = DB::table('product')->where('name','like','%'.$keywords.'%')->where('type_id',$type_id)->orderBy('sort_order','desc')->orderBy('id','desc')->paginate(15);
            }else{
                $list = DB::table('product')->where('type_id',$type_id)->orderBy('sort_order','desc')->orderBy('id','desc')->paginate(15);
            }
        }else{
            if(isset($_GET['keywords'])){
                $keywords = trim($_GET['keywords']);
                $list = DB::table('product')->where('name','like','%'.$keywords.'%')->orderBy('sort_order','desc')->orderBy('id','desc')->paginate(15);
            }else{
                $list = DB::table('product')->orderBy('sort_order','desc')->orderBy('id','desc')->paginate(15);
            }
        }
        // dd($list);
        // dump({{ $list->links() }});exit;
        $cate = BackstageModel::getCate('product_category',['pid'=>0 ]);
        foreach($list as $key=>$v){
            $typename = CommonModel::getOne('product_category',['id'=>$v->type_id]);
            // dump($typename->type_name);exit;
            $list[$key]->type_name = $typename->type_name;
        }
        return view('backstage/product/index',['cate'=>$cate,'list'=>$list]);
    }
    public function add(){
        $cate = BackstageModel::getCate('product_category',['pid'=>0 ]);
        return view('backstage/product/add',['cate'=>$cate]);
    }
    public function doadd(Request $request){
        if($request->isMethod('POST')){
            
            $data = $request->all();
            $files = $request->file('art_img');
            // dd($files);exit;
            if($data['type_id']==false || $data['name']=='' || $data['content']==''){
                $arrJson = array('status' => 0, 'message'=>'必要參數不能為空');
                return json_encode($arrJson);
            }else{
                $product['type_id'] = intval($data['type_id']);//必要參數
                $product['name'] = trim($data['name']);//必要參數
                $product['content'] = trim($data['content']);//必要參數
            }
            $product['weight'] = $data['weight'];
            $product['price'] = $data['price'];
            $product['offset'] = $data['offset'];
            $product['set'] = $data['set'];
            $product['url'] = $data['url'];
            $product['sort_order'] = $data['sort_order'];
            $product['info'] = $data['info'];
            $product['refund'] = $data['refund'];
            $product['is_show'] = $data['is_show'];
            $product['add_time'] = time();
            $newid = CommonModel::addDataGetId('product',$product);
            // 文件是否上傳成功
            if($files!=null && !empty($newid)){
                foreach($files as $key=>$file){
                    if ($file->isValid()){
                        // 獲取文件相關信息
                        $originalName = $file->getClientOriginalName(); // 文件原名
                        $ext = $file->getClientOriginalExtension();     // 擴展名

                        $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                        $type = $file->getClientMimeType();     // image/jpeg
                        // 上傳文件
                        $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                        // 将图片URL保存到数据库
                        $image['pid'] = $newid;
                        $image['img_url'] = '/uploads/product/'.$filename;
                        $image['add_time'] = time();
                        $res = CommonModel::addData('product_img',$image);
                        // 使用我們新建的uploads本地存儲空間（目錄）
                        $bool = Storage::disk('product')->put($filename, file_get_contents($realPath));
                        // if($bool!=true){
                        //     $arrJson = array('status' => 0, 'message'=>'圖片上傳失敗');
                        //     return json_encode($arrJson);
                        // }
                    }
                }
            }
            if($newid){
                $arrJson = array('status' => 1, 'message'=>'產品添加成功','jumpUrl'=>$this->redirectTo);
            }else{
                $arrJson = array('status' => 0, 'message'=>'產品添加失敗');
            }
            return json_encode($arrJson);
        }
    }
    public function edit($id){
        $table = 'product';
        $data =['id'=>$id];
        $pro = CommonModel::getOne($table,$data);
        $pro_imgs = CommonModel::getList('product_img',['id','img_url'],['pid'=>$id,'status'=>0]);
        // dd($pro_imgs);
        // dd(count($pro_imgs));
        $cate = BackstageModel::getCate('product_category',['pid'=>0 ]);
        // dd($cate);
        return view('backstage/product/edit',['cate'=>$cate,'pro_imgs'=>$pro_imgs,'pro'=>$pro]);
    }
    public function doedit(Request $request){
        if($request->isMethod('POST')){
            
            $data = $request->all();
            $files = $request->file('art_img');
            $id = $data['id'];
            // dd(trim($data['content']));
            if($data['type_id']==false || $data['name']=='' || $data['content']==''){
                $arrJson = array('status' => 0, 'message'=>'必要參數不能為空');
                return json_encode($arrJson);
            }else{
                // dd(trim($data['content']));
                $product['type_id'] = intval($data['type_id']);//必要參數
                $product['name'] = trim($data['name']);//必要參數
                $product['content'] = trim($data['content']);//必要參數
            }
            $flag = false;
            // 文件是否上傳成功
            if(!empty($files)){
                foreach($files as $key=>$file){
                    if ($file->isValid()){
                        // 
                        // 獲取文件相關信息
                        $originalName = $file->getClientOriginalName(); // 文件原名
                        
                        $ext = $file->getClientOriginalExtension();     // 擴展名

                        $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                        $type = $file->getClientMimeType();     // image/jpeg
                        // 上傳文件
                        $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                        // 将图片URL保存到数据库
                        $image['pid'] = $id;
                        $image['img_url'] = '/uploads/product/'.$filename;
                        $image['add_time'] = time();
                        $res = CommonModel::addData('product_img',$image);
                        // 使用我們新建的uploads本地存儲空間（目錄）
                        $bool = Storage::disk('product')->put($filename, file_get_contents($realPath));
                        if($bool==true){
                            $flag = true;
                        }
                        // if($bool!=true){
                        //     $arrJson = array('status' => 0, 'message'=>'圖片上傳失敗');
                        //     return json_encode($arrJson);
                        // }
                    }
                }
            }
            // dd($product['content']);
            $product['weight'] = $data['weight'];
            $product['price'] = $data['price'];
            $product['offset'] = $data['offset'];
            $product['set'] = $data['set'];
            $product['url'] = $data['url'];
            $product['sort_order'] = $data['sort_order'];
            $product['info'] = $data['info'];
            $product['refund'] = $data['refund'];
            $product['is_show'] = $data['is_show'];
            $product['up_time'] = time();
            // dd($product);
            $save = CommonModel::updateData('product',['id'=>$id],$product);
            if($save || $flag){
                $arrJson = array('status' => 1, 'message'=>'產品修改成功','jumpUrl'=>$this->redirectTo);
            }else{
                $arrJson = array('status' => 0, 'message'=>'產品修改失敗');
            }
            return json_encode($arrJson);
        }
    }

    // 刪除圖片
    public function dodel_img(Request $request){
        if($request->isMethod('POST')){
            $id=$request->input('id');
            if($id != ''){
                $res =CommonModel::updateData('product_img',['id'=>$id],['status'=>1 ]);
                if($res){
                    return response()->json(array('status' => 1,'message'=>'刪除成功'));
                }else{
                    return response()->json(array('status' => 0,'message'=>'刪除失敗'));
                }
            }
        }    
    }


}
